#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_wifi_api.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#include "MQTTClient.h"

static MQTTClient mq_client;
unsigned char *onenet_mqtt_buf = NULL;
unsigned char *onenet_mqtt_readbuf = NULL;
int buf_size;

Network n;
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;

// 消息回调函数（接收订阅主题的消息）
void mqtt_callback(MessageData *msg_data)
{
    if (msg_data == NULL) {
        printf("mqtt_callback: invalid message data\r\n");
        return;
    }

    printf("topic %.*s receive a message\r\n", 
           msg_data->topicName->lenstring.len, 
           msg_data->topicName->lenstring.data);
    printf("message is %.*s\r\n", 
           msg_data->message->payloadlen, 
           (char *)msg_data->message->payload);
}

int mqtt_connect(void)
{
    int rc = 0;
    char topicname[45] = "mqtt01-team12";  // 订阅/发布的主题（根据组别修改）

    // 初始化网络（依赖Paho MQTT的LiteOS适配层）
    NetworkInit(&n);
    // 连接EMQ公共MQTT服务器（无需注册，直接使用）
    NetworkConnect(&n, "broker.emqx.io", 1883);

    // 分配MQTT消息缓冲区（4096+1024=5120字节）
    buf_size = 4096 + 1024;
    onenet_mqtt_buf = (unsigned char *)malloc(buf_size);
    onenet_mqtt_readbuf = (unsigned char *)malloc(buf_size);
    if (!(onenet_mqtt_buf && onenet_mqtt_readbuf)) {
        printf("No memory for MQTT client buffer!\r\n");
        if (onenet_mqtt_buf) free(onenet_mqtt_buf);
        if (onenet_mqtt_readbuf) free(onenet_mqtt_readbuf);
        return -2;
    }

    // 初始化MQTT客户端
    MQTTClientInit(&mq_client, &n, 1000, 
                  onenet_mqtt_buf, buf_size, 
                  onenet_mqtt_readbuf, buf_size);

    // 启动MQTT后台任务（LiteOS适配层提供）
    MQTTStartTask(&mq_client);

    // 配置MQTT连接参数
    data.keepAliveInterval = 30;  // 心跳间隔30秒
    data.cleansession = 1;        // 清理会话（断开后不保留状态）
    data.clientID.cstring = "device12";  // 客户端ID（需唯一，根据组别修改）
    data.username.cstring = "device12";  // 用户名（自定义）
    data.password.cstring = "123456";    // 密码（自定义）

    // 设置默认消息回调函数
    mq_client.defaultMessageHandler = mqtt_callback;

    // 连接MQTT服务器
    rc = MQTTConnect(&mq_client, &data);
    if (rc != 0) {
        printf("MQTTConnect failed, rc=%d\r\n", rc);
        return rc;
    }
    printf("MQTT connected successfully!\r\n");

    // 订阅主题（QoS0等级）
    rc = MQTTSubscribe(&mq_client, topicname, 0, mqtt_callback);
    if (rc != 0) {
        printf("MQTTSubscribe failed, rc=%d\r\n", rc);
        return rc;
    }
    printf("Subscribed to topic: %s\r\n", topicname);

    // 循环发布消息（1秒/次）
    while (1) {
        MQTTMessage message;
        const char *payload = "hello team12-懒羊羊-Kitty-长江七号!";  // 发布的消息内容（可自定义）

        message.qos = 0;
        message.retained = 0;
        message.payload = (void *)payload;
        message.payloadlen = strlen(payload);

        // 发布消息
        if (MQTTPublish(&mq_client, topicname, &message) < 0) {
            printf("MQTTPublish failed!\r\n");
        } else {
            printf("Published message: %s\r\n", payload);
        }

        usleep(1000000);  // 休眠1秒
    }

    return 0;
}

void mqtt_test(void)
{
    mqtt_connect();
}
